package com.skyhigh.web.webservice.services;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.skyhigh.web.webservice.domain.Carga;
import com.skyhigh.web.webservice.domain.CargaList;
import com.skyhigh.web.webservice.domain.Contenedor;
import com.skyhigh.web.webservice.domain.ContenedorList;
import com.skyhigh.web.webservice.exceptions.ExceptionHelper;
import com.skyhigh.web.webservice.exceptions.RecordNotFoundException;
import com.skyhigh.web.webservice.exceptions.ServiceException;
import com.skyhigh.web.webservice.persistence.GenericDAO;

@Service("contenedorService")
@Transactional(
    propagation = Propagation.REQUIRED,
    rollbackFor = ServiceException.class,
    isolation = Isolation.DEFAULT,
    readOnly = false)
public class ContenedorServiceImpl implements ContenedorService {

	@Autowired
	@Qualifier("genericDao")
	private GenericDAO dao;
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	
	
	public Contenedor agregar(Contenedor entity) {
		dao.save(entity);
        return entity;
	}

	
	public void actualizar(Contenedor entity) {			
    	dao.update(entity);    	
	}

	
	public void eliminar(Integer id) {
		try {
			dao.deleteById(Contenedor.class, id);
		} catch (RecordNotFoundException e) {
			throw ExceptionHelper.newPrimaryKeyNotFountEx(id);
		}
	}
	
	@Transactional(readOnly = true)
	public Contenedor obtenerObjeto(Integer id) {
		Contenedor entity = dao.<Contenedor>get(Contenedor.class, id);
		if(entity == null){
    		throw ExceptionHelper.newPrimaryKeyNotFountEx();			
		}
    	
    	return entity;
	}

	@Transactional(readOnly = true)
	public ContenedorList obtenerObjetos() {
		List<Contenedor> entities = dao.getAll(Contenedor.class);    	
    	return new ContenedorList(entities);
	}
	
	public int obtenerCartidadObjetos() {
		int totalObjetos = dao.count(Contenedor.class);
		return totalObjetos;
	}	

	
	public int obtenerCartidadObjetosDespachadas() {
		String query = "FROM Contenedor WHERE idContenedor is not Null AND fechaSalida is not Null";
		List<Contenedor> entities = dao.find(query);
		int totalObjetos = entities.size();
		return totalObjetos;
	}


	@Transactional(readOnly = true)
	public ContenedorList obtenerObjetosByConsulta(String consultaSQL) {		
		List<Contenedor> entities = dao.find(consultaSQL);
		
		return new ContenedorList(entities);
	}

}
